// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    car: cc.Node = null
    carScript: cc.Component = null

    onLoad () {
      this.car = cc.find('Canvas/小车')
      this.carScript = this.car.getComponent('CarScript')
    }

    start () {
      this.node.on('touchstart', this.onTouchStart, this)
      this.node.on('touchmove', this.onTouchMove, this)
      this.node.on('touchend', this.onTouchEnd, this)
      this.node.on('touchcancle', this.onTouchCancle, this)
    }

    onTouchStart (e: cc.Event.EventTouch) {
      
    }
    onTouchMove (e: cc.Event.EventTouch) {
      let parent: cc.Node = this.node.getParent()
      // 将世界坐标转换为相对于父节点的相对坐标
      let pos: cc.Vec2 = parent.convertToNodeSpaceAR(e.getLocation())
      
      // 计算该点所在的方位 (cos, sin)
      let direction: cc.Vec2 = pos.normalize()
      // cc.log(`x:${direction.x}`, `y:${direction.y}`)
      // 将手柄限制在圆盘之内
      let maxR = 100 * 0.8
      let r :number = cc.Vec2.distance(pos, cc.v2(0, 0)) // 计算实际距离到圆心的距离
      if (r > maxR) {
        pos.x = maxR * direction.x
        pos.y = maxR * direction.y
      }

      this.node.setPosition(pos)

      // 操纵目标小车
      let radia = pos.signAngle(cc.v2(1, 0)) // 求两个向量的夹角弧度值
      let angle = radia / Math.PI * 180
      this.car.angle = -angle

      // 设置小车的方向
      this.carScript.direction = direction
    }
    onTouchEnd () {
      this.node.setPosition(cc.v3(0, 0, 0))
      this.carScript.direction = null
    }
    onTouchCancle () {
      
    }

    // update (dt) {}
}
